package org.geekbang.thinking.in.spring.generic;

import org.springframework.core.GenericCollectionTypeResolver;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * {@link GenericCollectionTypeResolver} 示例
 *
 * @author wangyh2
 * @version v1.0
 * @since 2021-12-01 15:18
 */
public class GenericCollectionTypeResolverDemo {
    private static StringList stringList;
    private static List<String> strings;

    public static void main(String[] args) throws NoSuchFieldException {
        // StringList extends ArrayList<String> 具体化
        // getCollectionType 返回具体化泛型参数类型集合的成员类型 = String
        Class<?> collectionType = GenericCollectionTypeResolver.getCollectionType(StringList.class);
        System.out.println(collectionType);

        // 没有具体泛型参数类型,所以返回null
        System.out.println(GenericCollectionTypeResolver.getCollectionType(ArrayList.class));

        // 获取字段
        Field field = GenericCollectionTypeResolverDemo.class.getDeclaredField("stringList");
        Class<?> collectionFieldType = GenericCollectionTypeResolver.getCollectionFieldType(field);
        System.out.println(collectionFieldType);

        field = GenericCollectionTypeResolverDemo.class.getDeclaredField("strings");
        collectionFieldType = GenericCollectionTypeResolver.getCollectionFieldType(field);
        System.out.println(collectionFieldType);
    }
}
